package com.pks.datacenter.handler;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.ohedu.base.model.UnitModel;
import org.ohedu.base.model.UserAuthorizedModel;
import org.ohedu.base.model.UserModel;
import org.ohedu.base.model.v2.AppModuleModel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.pks.datacenter.config.MyConfig;
import com.pks.datacenter.config.RedisKeyConfig;
import com.pks.datacenter.dto.YunUserDto;
import com.pks.datacenter.entity.user.User;
import com.pks.datacenter.utils.YunApiToken;
import com.pks.datacenter.utils.YunApiUtil;
import com.pks.resultful.common.SRemoteResult;
import com.thanone.base.common.DictionaryKeyConstant;
import com.thanone.base.common.model.DictionaryItemModel;

/**
 * 云平台的接口
 * 
 * @author zouchongjin@sina.com
 * @data 2014年8月22日
 */
@SuppressWarnings("unused")
@Component("yunHandler")
public class YunHandler {

	private static Logger logger = LoggerFactory.getLogger(YunHandler.class);

	public static final String LOG_TYPE_INSERT = "新增";
	public static final String LOG_TYPE_UPDATE = "更新";
	public static final String LOG_TYPE_DELETE = "删除";
	public static final String LOG_TYPE_SELECT = "查询";
	public static final String LOG_TYPE_OTHER = "其它";
	public static final String LOG_LEVEL_DEBUG = "调试";
	public static final String LOG_LEVEL_INFO = "一般";
	public static final String LOG_LEVEL_WARN = "警告";
	public static final String LOG_LEVEL_ERROR = "严重";

	@Autowired
	private RedisHandler redisHandler;
	

	// 获取用户信息（包括此用户是否为云平台中设置的应用管理员）
	public SRemoteResult<YunUserDto> findUserByToken(String token) {
		YunUserDto user = null;
		try {
//			String apiToken = YunApiUtil.getApiToken().getToken();
			UserModel um  = YunApiUtil.findUserByUserToken(getApiToken(),token,MyConfig.moduleId);
			if (um != null) {
				if (um.getUserAuth() == null || UserAuthorizedModel.STATE_USING != um.getUserAuth().getState() || UserAuthorizedModel.ROLE_ADMIN != um.getUserAuth().getRole()) {
					return SRemoteResult.initErrorNoPerm();
				}
				user = YunUserDto.convert(um);
			} else {
				return SRemoteResult.initError("请先登录");
			}
		} catch (Exception e) {
			
		}
		return SRemoteResult.initSuccess(user);
	}
	
	
	public List<UserModel> findUsersHaveUnitInfo() {
		List<UserModel> list = new ArrayList<UserModel>();
		boolean bool = true;
		int start = 0 ;
		int pagesize = 2000;
		List<UserModel> temp ;
		while(bool) {
			temp = YunApiUtil.findUsersHaveUnitInfo(getApiToken(), null, null, null, null, null, null, false, null, true, start, pagesize, null);
			if(temp.size()<pagesize){
				bool = false;
			}else{
				start = start + pagesize;
			}
			list.addAll(temp);
		}
		return list;
	}
	
	public List<UserModel> findModuleUsers(Date afterTime, int offset, int pagesize) {
		return YunApiUtil.findModuleUsers(getApiToken(), null, null, null, null, afterTime, MyConfig.moduleId, null, null, offset, pagesize, null, null);
	}
	
	public List<UserModel> findModuleUsers(Date afterTime) {
		List<UserModel> list = new ArrayList<UserModel>();
		boolean bool = true;
		int start = 0 ;
		int pagesize = 2000;
		List<UserModel> temp ;
		while(bool) {
			temp = YunApiUtil.findModuleUsers(getApiToken(), null, null, null, null, afterTime, MyConfig.moduleId, null, null, start, pagesize, null, null);
			if(temp.size()<pagesize){
				bool = false;
			}else{
				start = start + pagesize;
			}
			list.addAll(temp);
		}
		return list;
	}


	public List<AppModuleModel> findAppModuleList() {
		return YunApiUtil.findAppModuleList(getApiToken(),null,null,null);
	}


	public List<DictionaryItemModel> findDicItemByKey(String key) {
		return YunApiUtil.findDicItemByKey(getApiToken(),key);
	}


	public List<UnitModel> findUnits() {
		return YunApiUtil.findUnits(getApiToken(),null, null, null, null, null, null, null, null, null, null, null, null, null, null);
	}
	
	
	public String getApiToken() {
		YunApiToken yunApiToken = null;
		Object obj = redisHandler.get(RedisKeyConfig.KEY_YUN_APITOKEN);
		if (obj != null) {
			yunApiToken = (YunApiToken) obj;
		}
		if(yunApiToken==null || yunApiToken.getEndtime()<new Date().getTime()){
			yunApiToken = YunApiUtil.getApiTokenFromYun();
			yunApiToken.setEndtime(System.currentTimeMillis()+yunApiToken.getEffective()-10*60*1000);
			redisHandler.set(RedisKeyConfig.KEY_YUN_APITOKEN ,yunApiToken, 2 * 3600);
		}
		return yunApiToken.getToken();
	}
	
}
